<?php


namespace modules\english;

use constant\migrate\English;
use entity\db\EntityEnglishNotes;
use model\english\EnglishDb;
use modules\es\EnglishEs;

class WordsReader
{

    public static function read()
    {
        $file = English::WORDS_FILE_PATH;

        $file = file_get_contents($file);

        $pattern = "/\[\[.*\]\]/";

        $rows = preg_split($pattern, $file);
        $rows = array_values(array_filter($rows));

        preg_match_all($pattern, $file, $tags);
        $tags = current($tags);

        $data = [];
        $wordPattern = "/\d+\./";
        foreach ($tags as $index => $tag) {
            $words = $rows[$index] ?? '';
            $main_tag = preg_replace("/[][]/", "", $tag);

            $splitWords = preg_split($wordPattern, $words);
            $splitWords = array_values(array_filter($splitWords));

            if (!$splitWords) continue;
            foreach ($splitWords as $wordContent) {
                $wordContent = trim($wordContent);
                if (!$wordContent) continue;
                preg_match("/^[a-zA-Z]*/", $wordContent, $word);
                if (empty($word[0])) continue;

                $entity = new EntityEnglishNotes();
                $entity->title = $word[0];
                $entity->main_tag = $main_tag;
                $entity->content = $wordContent;
                $data[] = $entity;
            }
        }

        \model\english\EnglishNotesDb::wordsMultipleSave($data);
    }

}